<template>
  <el-card class="mainContainer" shadow="never">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="changeTabClick">


      <el-tab-pane label="数据类型参数配置" name="first">
          <div ref="searchRef">
            <el-form :inline="true"
                     ref="formDataArgsSelectRef"
                     :model="formDataArgsSelect"
                     v-show="showDataArgsSearch"
                     class="demo-form-inline animate__animated animate__fadeIn">
              <el-form-item label="数据类型名称：">
                <el-input v-model="formDataArgsSelect.name" placeholder="数据类型名称" clearable/>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="queryDataArgsTable">查询</el-button>
                <el-button type="info" @click="queryDataArgsTable">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-row :gutter="10" class="margin-bottom-18"
                  style="margin-left: 0;margin-right: 0"
                  type="flex" justify="space-between">
            <el-col :span="1.5" style="padding: 0">
              <el-button
                  type="primary"
                  :icon="Message"
                  size=small
                  @click="postArgsData"
              >新增数据类型
              </el-button>
            </el-col>

            <el-col :span="1.5" style="padding: 0">
              <RightToolbar :show-search="showDataArgsSearch"
                            @updateShowSearch="updateShowDataArgsSearch"
                            @queryTable="queryDataArgsTable"/>
            </el-col>
          </el-row>


          <el-table :data="argsTableData" border
                    :height=max_table_height
                    row-key="id"
                    cell-class-name="custom_table_column"
                    style="width: 100%">
            <el-table-column prop="name" align="center" label="数据类型名称"/>
            <el-table-column prop="value" align="center" label="数据类型值"/>
            <el-table-column prop="index" align="center" label="数据类型排序"/>
            <el-table-column prop="category" align="center" label="数据类型的分类">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="auto">
                  <template #default>
                    <el-scrollbar max-height="300px">

                      <el-text style="white-space:pre-wrap;" v-for="item in scope.row.category">{{
                          item.name + '\n'
                        }}
                      </el-text>
                    </el-scrollbar>
                  </template>
                  <template #reference>
                    <el-text>{{ scope.row.category.length }}</el-text>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" label="JSON参数">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="auto">
                  <template #default>
                    <el-scrollbar max-height="300px">
                      <el-text style="white-space:pre-wrap;" truncated>{{ scope.row.args }}</el-text>
                    </el-scrollbar>
                  </template>
                  <template #reference>
                    <el-text truncated>{{ scope.row.args }}</el-text>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" label="数据类型描述">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="auto">
                  <template #default>
                    <!--                        <div>{{ scope.row.description }}</div>-->
                    <el-scrollbar max-height="300px">
                      <el-text style="white-space:pre-wrap;" truncated>{{ scope.row.description }}</el-text>
                    </el-scrollbar>
                  </template>
                  <template #reference>
                    <el-text truncated>{{ scope.row.description }}</el-text>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" label="是否可用">
              <template #default="scope">
                <el-switch v-model="scope.row.isEnable"
                           @change="updateArgsDataIsEnable(scope.row.id,scope.row.isEnable)"/>
              </template>
            </el-table-column>
            <el-table-column prop="creator" align="center" label="创建人"/>
            <el-table-column prop="create_time" align="center" label="创建时间"/>
            <el-table-column prop="modifier" align="center" label="修改人"/>
            <el-table-column prop="update_time" align="center" label="修改时间"/>
            <el-table-column align="center" label="操作" width="200px">
              <template #default="scope">
                <el-button size="small"
                           @click="UpdateArgsData(scope.row.id)"
                           type="primary"
                >编辑
                </el-button>
                <el-button
                    size="small"
                    @click="deleteArgsData(scope.row.id)"
                    type="danger">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>


          <el-row :gutter="10" class="margin-top-18"
                  style="margin-left: 0;margin-right: 0"
                  type="flex" justify="space-between">
            <el-col :span="1.5">
            </el-col>
            <el-col :span="1.5">
              <el-pagination
                  layout="total, sizes, prev, pager, next "
                  :page-sizes="[10, 20, 50, 100]"
                  v-model:current-page="formDataArgsSelect.page"
                  v-model:page-size="formDataArgsSelect.page_size"
                  @size-change="argsDataSizeChange"
                  @current-change="argsDataCurrentChange"
                  :total="formDataArgsSelect.total"/>
            </el-col>
          </el-row>


        <!--  新建/编辑框 数据类型-->
        <el-dialog
            v-model="argsDialog"
            :title="argsDialogTitle"
            width="50%"
        >
          <!--    <span>This is a message</span>-->
          <el-form :model="argsFormDate"
                   ref="argsDialogRef"
                   :rules="argsRules"
                   label-width="130px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="数据类型名称: ">
                  <el-input v-model.trim="argsFormDate.name"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="数据类型值: ">
                  <el-input v-model.trim="argsFormDate.value"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="数据类型排序: "
                              prop="index"
                              :rules="[{ type: 'number', message: '必须是数字' },]">
                  <el-input v-model.number="argsFormDate.index"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="数据类型分类: ">
                  <el-select v-model="argsFormDate.category" style="width: 100%"
                             filterable multiple
                             collapse-tags collapse-tags-tooltip
                             placeholder="选择数据类型分类" size="large">
                    <el-option
                        v-for="item in catOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="JSON参数: " prop="args">
                  <el-input type="textarea" @input="changeArgs"
                            v-model.trim="argsFormDate.args"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="数据类型描述: ">
                  <el-input type="textarea" v-model.trim="argsFormDate.description"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="是否可用: ">
                  <el-switch v-model="argsFormDate.isEnable"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="是否可下载: ">
                  <el-switch v-model="argsFormDate.isDownload"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="是否直接生成数据: ">
                  <el-switch v-model="argsFormDate.isNoArgs"/>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>


          <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelArgsDialog">取消</el-button>
        <el-button type="primary" @click="commitArgsDialog(argsDialogRef)">确定</el-button>
      </span>
          </template>
        </el-dialog>

      </el-tab-pane>


      <el-tab-pane label="数据分类" name="second">
        <el-scrollbar height="calc(100vh - 220px)">
          <el-form :inline="true"
                   ref="formDataCatSelectRef"
                   :model="formDataCatSelect"
                   v-show="showCatDataSearch"
                   class="demo-form-inline animate__animated animate__fadeIn">
            <el-form-item label="分类名称：">
              <el-input style="width: 200px" v-model="formDataCatSelect.name" placeholder="分类名称" clearable/>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="queryDataCatTable">查询</el-button>
              <el-button type="info" @click="resetDataCatSelect(formDataCatSelectRef)">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="margin-bottom-18"
                  style="margin-left: 0;margin-right: 0"
                  type="flex" justify="space-between">
            <el-col :span="1.5" style="padding: 0">
              <el-button
                  type="primary"
                  :icon="Message"
                  size=small
                  @click="catDialog = true;catDialogTitle='新增分类'"
              >新增分类
              </el-button>
            </el-col>

            <el-col :span="1.5" style="padding: 0">
              <RightToolbar :show-search="showCatDataSearch"
                            @updateShowSearch="updateShowCatDataSearch"
                            @queryTable="queryDataCatTable"/>
            </el-col>
          </el-row>


          <div class="affix-container" style="max-height: calc(100vh - 270px);">
            <el-affix target=".affix-container" :offset="120">
              <el-table :data="CatTableData" border
                        row-key="id"
                        max-height="calc(100vh - 320px)"
                        header-cell-class-name="custom_table_header"
                        cell-class-name="custom_table_column"
                        style="width: 100%">
                <el-table-column prop="name" align="center" label="分类名称"/>
                <el-table-column prop="index" align="center" label="分类排序"/>
                <el-table-column prop="creator" align="center" label="创建人"/>
                <el-table-column prop="create_time" align="center" label="创建时间"/>
                <el-table-column prop="modifier" align="center" label="修改人"/>
                <el-table-column prop="update_time" align="center" label="修改时间"/>
                <el-table-column align="center" label="操作" width="200px">
                  <template #default="scope">
                    <el-button size="small"
                               @click="UpdateCatData(scope.row.id)"
                               type="primary">编辑
                    </el-button>
                    <el-button
                        size="small"
                        @click="deleteCatData(scope.row.id)"
                        type="danger">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-affix>
          </div>


          <el-row :gutter="10" class="margin-top-18"
                  style="margin-left: 0;margin-right: 0"
                  type="flex" justify="space-between">
            <el-col :span="1.5">
            </el-col>
            <el-col :span="1.5">
              <el-pagination
                  layout="total, sizes, prev, pager, next "
                  :page-sizes="[10, 20, 50, 100]"
                  v-model:current-page="formDataCatSelect.page"
                  v-model:page-size="formDataCatSelect.page_size"
                  @size-change="catDataSizeChange"
                  @current-change="catDataCurrentChange"
                  :total="formDataCatSelect.total"/>
            </el-col>
          </el-row>
        </el-scrollbar>


        <!--  新建/编辑框 数据分类-->
        <el-dialog
            v-model="catDialog"
            :title="catDialogTitle"
            width="30%"
        >
          <!--    <span>This is a message</span>-->
          <el-form :model="catFormDate"
                   ref="catDialogRef"
                   label-width="80px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="分类名称: ">
                  <el-input v-model.trim="catFormDate.name"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="分类排序: "
                              prop="index"
                              :rules="[{ type: 'number', message: '必须是数字' },]">
                  <el-input v-model.number="catFormDate.index"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>


          <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelCatDialog">取消</el-button>
        <el-button type="primary" @click="commitCatDialog(catDialogRef)">确定</el-button>
      </span>
          </template>
        </el-dialog>

      </el-tab-pane>


    </el-tabs>

  </el-card>

</template>

<script setup>

import RightToolbar from '@/components/RightToolbar/index.vue'
import {ref, reactive, onMounted, onUnmounted, nextTick} from 'vue'
import {
  Message,
  Delete
} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {
  getDataCat,
  getDataCatById,
  postDataCat,
  patchDataCat,
  getDataArgs,
  getCatOptions,
  postDataArgs,
  getDataArgsById,
  updateDataArgs, deleteDataCat, deleteDataArgs, updateDataArgsIsEnable,
} from "@/apis/dataGeneration/dataGenerationConfig.js";

// TAB 活跃
const activeName = ref('first')

const changeTabClick = (tab, event) => {
  console.log(tab, event)
}


const searchRef = ref(null)
const max_table_height = ref("calc(100vh - 400px)")

const update_max_table_height = () => {
  max_table_height.value = "calc(100vh - 300px - " + searchRef.value.clientHeight + "px)"
}

onMounted(() => {
  update_max_table_height();
  addEventListener("resize", update_max_table_height);
})
onUnmounted(() => {
  removeEventListener("resize", update_max_table_height);
})


//  数据类型参数配置
const showDataArgsSearch = ref(true)
const updateShowDataArgsSearch = () => {
  showDataArgsSearch.value = !showDataArgsSearch.value
  nextTick(update_max_table_height);
}


const formDataArgsSelectRef = ref()
let formDataArgsSelect = reactive({
  name: '',
  page: 1,
  page_size: 10,
  total: 0
})

let argsTableData = ref([])
const queryDataArgsTable = () => {
  getDataArgs(qs.stringify(formDataArgsSelect)).then(res => {
    argsTableData.value = res.data.data;
    formDataArgsSelect.page = res.data.page;
    formDataArgsSelect.page_size = res.data.pagesize;
    formDataArgsSelect.total = res.data.total;
  })
}

const resetDataArgsSelect = (formEl) => {
  formDataArgsSelect = {
    name: '',
    page: 1,
    page_size: 10,
    total: 0
  }
}
onMounted(() => {
  queryDataArgsTable();
})
const argsDataSizeChange = () => {
  queryDataArgsTable();
}

const argsDataCurrentChange = (value) => {
  queryDataArgsTable();
}

const argsDialogRef = ref()
const argsDialog = ref(false)
const argsDialogTitle = ref("")
const argsFormDate = ref({})
let catOptions = ref([])

const checkArgs = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请填写JSON数据'))
  }
  setTimeout(() => {
    // 判断是否JSON数据
    try {
      console.log(JSON.parse(argsFormDate.value.args))
      callback()
    } catch (e) {
      console.log(e.message)
      callback(new Error('JSON格式错误'))
    }
  }, 1000)
}

const argsRules = reactive({
  args: [{validator: checkArgs, trigger: 'blur'}],
})
const postArgsData = () => {
  argsDialog.value = true;
  argsDialogTitle.value = '新增数据类型';
  argsFormDate.value.isEnable = true;
  argsFormDate.value.isDownload = false;
  argsFormDate.value.isNoArgs = false;
  getCatOptions().then(res => {
    catOptions.value = res.data;
  })
}

const changeArgs = () => {

}

const cancelArgsDialog = () => {
  argsDialog.value = false;
  argsFormDate.value = {};
}

const commitArgsDialog = (formEl) => {

  formEl.validate((valid) => {
    if (valid) {
      argsDialog.value = false;
      // argsFormDate.value.args = JSON.parse(argsFormDate.value.args)
      if (argsFormDate.value.id) {
        updateDataArgs(argsFormDate.value).then(res => {
          ElMessage({
            message: '操作成功',
            type: 'success',
          });
          argsFormDate.value = {};
          queryDataArgsTable();
        })
      } else {
        postDataArgs(argsFormDate.value).then(res => {
          ElMessage({
            message: '操作成功',
            type: 'success',
          });
          argsFormDate.value = {};
          queryDataArgsTable();
        })
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const UpdateArgsData = (id) => {
  argsDialog.value = true;
  argsDialogTitle.value = "编辑数据类型"
  getCatOptions().then(res => {
    catOptions.value = res.data;
  })

  getDataArgsById(id).then(res => {
    argsFormDate.value.id = res.id;
    argsFormDate.value.name = res.name;
    argsFormDate.value.value = res.value;
    argsFormDate.value.index = res.index;
    argsFormDate.value.category = [];
    if (res.category.length > 0) {
      res.category.forEach((v, i) => {
        argsFormDate.value.category.push(v.value)
      })
    }
    argsFormDate.value.args = res.args;
    argsFormDate.value.description = res.description;
    argsFormDate.value.isEnable = res.isEnable;
    argsFormDate.value.isDownload = res.isDownload;
    argsFormDate.value.isNoArgs = res.isNoArgs;
  })
}

const deleteArgsData = (id) => {
  ElMessageBox.confirm('是否删除该数据？', '删除数据', {confirmButtonText: '确定', cancelButtonText: "取消"})
      .then(() => {
        deleteDataArgs({"id": id}).then(res => {
          ElMessage({
            message: '删除成功',
            type: 'success',
          });
          queryDataArgsTable();
        });

        done();
      })
      .catch(() => {
        // catch error
      })

}

const updateArgsDataIsEnable = (id, isEnable) => {
  updateDataArgsIsEnable({"id": id, "isEnable": isEnable}).then(res => {
    ElMessage({
      message: '操作成功',
      type: 'success',
    });
    queryDataArgsTable();
  })
}



//  数据分类
const showCatDataSearch = ref(true)
const updateShowCatDataSearch = () => {
  showCatDataSearch.value = !showCatDataSearch.value;
}

const formDataCatSelectRef = ref()
let formDataCatSelect = reactive({
  name: '',
  page: 1,
  page_size: 10,
  total: 0
})

let CatTableData = ref([])
const queryDataCatTable = () => {
  getDataCat(qs.stringify(formDataCatSelect)).then(res => {
    CatTableData.value = res.data.data;
    formDataCatSelect.page = res.data.page;
    formDataCatSelect.page_size = res.data.pagesize;
    formDataCatSelect.total = res.data.total;
  })
}

const resetDataCatSelect = (formEl) => {
  console.log(22)
  formDataCatSelect = {
    name: '',
    page: 1,
    page_size: 10,
    total: 0
  }
}
onMounted(() => {
  queryDataCatTable();
})
const catDataSizeChange = () => {
  queryDataCatTable();
}

const catDataCurrentChange = (value) => {
  queryDataCatTable();
}


const catDialogRef = ref()
const catDialog = ref(false)
const catDialogTitle = ref("")
const catFormDate = ref({})

const cancelCatDialog = () => {
  catDialog.value = false;
  catFormDate.value = {};
}

const commitCatDialog = (formEl) => {

  formEl.validate((valid) => {
    if (valid) {
      catDialog.value = false;
      if (catFormDate.value.id) {
        patchDataCat(catFormDate.value.id, catFormDate.value).then(res => {
          ElMessage({
            message: '操作成功',
            type: 'success',
          });
          catFormDate.value = {};
          queryDataCatTable();
        })
      } else {
        postDataCat(catFormDate.value).then(res => {
          ElMessage({
            message: '操作成功',
            type: 'success',
          });
          catFormDate.value = {};
          queryDataCatTable();
        })
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const UpdateCatData = (id) => {
  catDialog.value = true;
  catDialogTitle.value = "编辑分类"

  getDataCatById(id).then(res => {
    catFormDate.value.id = res.id;
    catFormDate.value.name = res.name;
    catFormDate.value.index = res.index;
  })
}

const deleteCatData = (id) => {
  ElMessageBox.confirm('是否删除该数据？', '删除数据', {confirmButtonText: '确定', cancelButtonText: "取消"})
      .then(() => {
        deleteDataCat(id).then(res => {
          ElMessage({
            message: '删除成功',
            type: 'success',
          });
          queryDataCatTable();
        });

        done();
      })
      .catch(() => {
        // catch error
      })

}




</script>

<style lang="scss" scoped>

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}


</style>
